import random

from fastapi import Depends, BackgroundTasks

from app.config import config
from app.dependencies import Dependencies
from app.schemas.codeSchemas import SendCodeRequest, CodeTargetType
from app.utils.email import EmailServer


class CodeLogic:
    def __init__(self,
                 background_tasks: BackgroundTasks,
                 email_server: EmailServer = Depends(),
                 redis_client=Depends(Dependencies.get_logger)
                 ):
        self.email_server = email_server
        self.background_tasks = background_tasks
        self.redis_client = redis_client

    async def send_code(self, email_data: SendCodeRequest, logger):
        """
        发送验证码
        """
        # 生成验证码 6 位长度
        code: str = ''.join(str(random.randint(0, 9)) for _ in range(6))
        # 保存到 redis 设置过期时间 1分钟
        await self.redis_client.set(email_data.email, code, ex=config.code.expire)

        match email_data.target_type:
            case CodeTargetType.EMAIL:
                # 邮箱验证
                self.background_tasks.add_task(self.email_server.send_email, email_data.email, code, logger)
